import {call, Loading, Module, register, SagaGenerator} from "../core-native";
import LoginPage from "../pages/LoginPage";
import {RootState} from "../types";
import {emits, storages} from "../constants";
import AsyncStorage from "@react-native-async-storage/async-storage";
// @ts-ignore
import RCTNativeAppEventEmitter from "react-native/Libraries/EventEmitter/RCTNativeAppEventEmitter";
import {LOADING_LOGIN} from "../constants/loadingKey";

class LoginModule extends Module<RootState, "login"> {
    *onEnter(): SagaGenerator {
        console.log("登录页面onEnter");
    }
    *onDestroy(): SagaGenerator {
        console.log("登录页面onDestroy");
    }
    /**
     * 登录请求
     * @param username 用户名
     * @param password 密码
     */
    @Loading(LOADING_LOGIN)
    *loginRequest(username: string, password: string) {
        const res: any = yield* call(
            () =>
                new Promise(resolve => {
                    console.log("模拟ajax请求: ", username, password);
                    setTimeout(() => {
                        resolve({
                            userinfo: {nickname: "VegaChen", age: 26, money: 520},
                            token: "test-token",
                        });
                    }, 2000);
                })
        );
        if (res) {
            yield* call(() => AsyncStorage.setItem(storages.KEY_USERINFO, JSON.stringify(res.userinfo)));
            yield* call(() => AsyncStorage.setItem(storages.KEY_TOKEN, JSON.stringify(res.token)));
            RCTNativeAppEventEmitter.emit(emits.EMIT_LOGIN_SUCCESS);
        }
    }
}

const module = register(new LoginModule("login", {}));
export const LoginActions = module.getActions();
export const Login = module.attachLifecycle(LoginPage);
